<template>
  <div>
    <div id="list-item" ref="form">
      <el-form :inline="true">
        <el-form-item>
          <el-input placeholder="请输入电话" clearable v-model="phone" @keyup.enter.native="onConfirm">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-input placeholder="请输入IP地址" clearable v-model="ip" @keyup.enter.native="onConfirm">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-input placeholder="请输入备注" clearable v-model="info" @keyup.enter.native="onConfirm">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onConfirm">确认</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="onClear">清空</el-button>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button @click.native.prevent="onDirectConnect(directIp)">
            联机
          </el-button>
        </el-form-item>
        <el-form-item style="float: right">
          <el-input placeholder="请输入IP地址" v-model="directIp" @keyup.enter.native="onDirectConnect(directIp)" clearable>
          </el-input>
        </el-form-item>
      </el-form>
    </div>

    <el-table ref="table" :data="tableData" :max-height="maxTableHeight" border style="width: 100%" v-loading="loading">
      <el-table-column type="index" width="50">
        <template slot-scope="scope">
          {{ tableData.length - scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="时间" width="160">
        <template slot-scope="{row}">
          <span>{{ row.create_time| dateFormat('yyyy-MM-dd hh:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="120">
      </el-table-column>
      <el-table-column prop="dept_name" label="科室" width="150">
      </el-table-column>
      <el-table-column prop="ip" label="IP地址" width="120">
      </el-table-column>
      <el-table-column prop="info" label="备注">
      </el-table-column>
      <el-table-column prop="status" sortable label="状态" width="80">
        <template slot-scope="{row}">
          <el-tag :type="statusMap[row.status].type">
            {{ statusMap[row.status].description }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              @click.native.prevent="onConnect(scope.row.ip)"
              size="small"
              v-if="scope.row.ip !== ''">
            联机
          </el-button>
          <el-button
              @click.native.prevent="handleFinish(scope.row)"
              type="success"
              size="small"
              v-if="scope.row.status === '0'">
            完成
          </el-button>
          <el-button
              @click.native.prevent="handleUpdate(scope.row, scope.$index)"
              type="primary"
              size="small">
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="编辑" :visible.sync="dialogFormVisible">
      <!--          :rules="rules" 自定义验证规则-->
      <el-form
          ref="dataForm"
          :model="temp"
          label-position="left"
          label-width="120px"
          style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="电话：" prop="phone">
          <el-input v-model="temp.phone" @keyup.enter.native="updateData" clearable />
        </el-form-item>
        <el-form-item label="IP地址：" prop="ip">
          <el-input v-model="temp.ip" @keyup.enter.native="updateData" clearable />
        </el-form-item>
        <el-form-item label="备注：" prop="info">
          <el-input v-model="temp.info" @keyup.enter.native="updateData" clearable />
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-select v-model="temp.status" class="filter-item" placeholder="请选择状态">
            <el-option key="'0'" label="未完成" :value="'0'" />
            <el-option key="'1'" label="已完成" :value="'1'" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateData">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { handleConnect } from '@/utils'
import { v4 as uuidv4 } from 'uuid'

export default {
  name: 'home-page',
  mounted () {
    setTimeout(() => {
      this.maxTableHeight = window.innerHeight - this.$refs.form.offsetHeight - 20
    }, 0)
    let that = this
    window.onresize = () => {
      return (() => {
        that.maxTableHeight = window.innerHeight - that.$refs.form.offsetHeight - 20
      })()
    }
  },
  created () {
    let userId = sessionStorage.getItem('user_id')
    // 初始化时加载当日数据
    // 获取当日零点时间
    const startTimeStamp = new Date(new Date().toLocaleDateString()).getTime()
    this.loading = true
    var self = this
    this.$pool.query('select * from record where create_time>? and submit_user_id=? order by create_time desc', [startTimeStamp, userId], function (err, rows) {
      if (err) {
        console.log(err)
      }
      self.tableData = JSON.parse(JSON.stringify(rows))
      self.loading = false
    })
  },
  data () {
    return {
      maxTableHeight: 0,
      phone: '',
      ip: '',
      info: '',
      directIp: '',
      tableData: [],
      loading: false,
      statusMap: [
        {
          description: '未完成',
          type: 'info'
        },
        {
          description: '已完成',
          type: 'success'
        }
      ],
      dialogFormVisible: false,
      temp: {
        record_id: '',
        phone: '',
        ip: '',
        info: '',
        status: undefined,
        createTime: undefined,
        updateTime: undefined
      }
    }
  },
  filters: {
    dateFormat (date, fmt) {
      date = new Date(date)
      let o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds() // 毫秒
      }
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
      }
      for (let k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
        }
      }
      return fmt
    }

  },
  methods: {
    isValidIp (ip) {
      return /^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/.test(ip)
    },
    resetForm () {
      this.phone = ''
      this.ip = ''
      this.info = ''
    },
    onConfirm () {
      /**
       * 1. 若ip为空，跳到4；若非空，跳到2
       * 2. 检测ip格式，若ip格式错误，提示错误并重新输入，直到正确后跳到3
       * 3. 打开radmin
       * 4. 记录到数据库
       */
      // 备注和电话必须有一项
      if (!this.info && !this.phone) {
        this.$message.error({
          message: '请填入电话或备注',
          duration: 800
        })
        return
      }

      if (this.ip) {
        if (!this.isValidIp(this.ip)) {
          this.$message.error({
            message: 'IP地址格式错误，请重新输入',
            duration: 800
          })
          return
        }
        // 打开radmin
        console.log('连接radmin')
        handleConnect(this.ip)
      }
      let formData = {
        record_id: uuidv4(),
        create_time: new Date().getTime(),
        update_time: new Date().getTime(),
        phone: this.phone,
        ip: this.ip,
        info: this.info,
        status: '0' // 0为未完成，1为已完成
      }
      // 保存到数据库
      var self = this
      this.loading = true
      this.$pool.query('select dept_id,dept_name from dept where phone=?', [formData.phone], function (err, rows) {
        if (err) {
          self.$message.error({
            message: err,
            duration: 800
          })
          return
        }
        let deptId = ''
        let deptName = ''
        if (rows.length > 0) {
          deptId = rows[0].dept_id
          deptName = rows[0].dept_name
          formData.dept_id = deptId
          formData.dept_name = deptName
        }
        let userId = sessionStorage.getItem('user_id')
        const insertSql = 'insert into record(record_id, create_time, update_time, phone, ip, info ,status, dept_id, dept_name,submit_user_id) values (?,?,?,?,?,?,?,?,?,?)'
        const values = [formData.record_id, formData.create_time, formData.update_time, formData.phone, formData.ip, formData.info, formData.status, deptId, deptName, userId]
        self.$pool.query(insertSql, values, function (err, result) {
          if (err) {
            // todo 处理报错
            self.$message.error({
              message: err,
              duration: 800
            })
            return
          }
          self.tableData.unshift(formData)
          self.loading = false
        })
      })
      this.resetForm()
      // this.$nextTick(() => {
      //   let container = this.$el.querySelector('.el-table__body-wrapper')
      //   container.scrollTop = container.scrollHeight
      // })
    },
    onClear () {
      this.resetForm()
    },
    onDirectConnect (ip) {
      handleConnect(ip)
    },
    handleFinish (row) {
      let recordId = row.record_id
      this.$pool.query('update record set status=?, update_time=? where record_id=?', ['1', new Date().getTime(), recordId], function (err, result) {
        if (!err) {
          console.log(result)
        }
        console.log(err)
      })
      row.status = '1'
    },
    handleUpdate (row, index) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.index = index
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData () {
      let self = this
      this.$refs['dataForm'].validate((valid) => {
        // todo 统一验证
        if (valid) {
          if (this.temp.ip) {
            if (!this.isValidIp(this.temp.ip)) {
              this.$message.error({
                message: 'IP地址格式错误，请重新输入',
                duration: 800
              })
              return
            }
          }
          let updateSql = 'update record set phone=?, info=?, status=?, ip=?, update_time=? where record_id=?'
          let params = [this.temp.phone, this.temp.info, this.temp.status, this.temp.ip, new Date().getTime(), this.temp.record_id]
          this.$pool.query(updateSql, params, function (err, result) {
            if (!err) {
              console.log(self.temp)
              self.$set(self.tableData, self.temp.index, self.temp)
            }
          })
          this.dialogFormVisible = false
          this.$notify({
            title: '操作成功',
            message: '修改信息成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    onConnect (ip) {
      handleConnect(ip)
    }
  }
}
</script>

<style>
/* CSS */
.el-table {
  width: 99.9% !important;
}
</style>
